package com.study.service.impl;

import com.study.constant.Constants;
import com.study.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author mjy
 * @date 2021/12/07
 * @description
 */
@Service
public class RedisServiceImpl implements RedisService {


    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;


    @Override
    public void setKey(String key, Object value, long timeout, TimeUnit timeUnit) {

        ValueOperations<Object, Object> ops = redisTemplate.opsForValue();
        ops.set(key, value);
        if (timeout > 0) {
            redisTemplate.boundValueOps(key).expire(timeout, timeUnit);
        }
    }

    @Override
    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public void deleteKey(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public void setHash(String key, Map<String, Object> map, Long timeout, TimeUnit timeUnit) {
        if (timeout > 0) {
            redisTemplate.opsForHash().putAll(key, map);
        } else {
            redisTemplate.expire(key, timeout, timeUnit);
        }
    }

    @Override
    public Map<Object, Object> getHashValue(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    @Override
    public void saveCommand(String imei, String commandNumber, Object object) {
        String key= Constants.COMMAND_PREFIX+imei;
        Map<Object, Object> map = redisTemplate.opsForHash().entries(key);
        if (map==null){
            map=new HashMap<>();
        }
        map.put(commandNumber,object);
        redisTemplate.opsForHash().putAll(key,map);
    }


}
